package com.thtf.openguess.controller;

import com.google.common.base.Stopwatch;
import com.thtf.openguess.service.TestAllService;
import com.thtf.openguess.util.ApiResult;
import com.thtf.openguess.util.QueryParam;
import com.thtf.openguess.util.QueryVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * 测试数据库
 */
@RestController
@RequestMapping("/openguess/testAll")
@Api(value = "测试数据库",tags = "测试数据库")
@Slf4j
public class TestAllController {

    @Resource
    private JdbcTemplate jdbcTemplate;

    @Resource
    private TestAllService service;

    @PostMapping("/query")
    @CrossOrigin
    @ApiOperation(value = "查询测试",notes = "查询测试")
    public ApiResult testQuery(@RequestBody QueryParam queryParam){

        if (StringUtils.isBlank(queryParam.getSql())){
            return ApiResult.fail("请输入sql!");
        }
        log.info("接收参数sql:==============" + queryParam.getSql());
//        String sql = queryParam.getSql().replaceAll("\n", " ");
//        log.info("转义接收参数sql:==============" + sql);
//        queryParam.setSql(sql);
        Stopwatch started = Stopwatch.createStarted();
        List<Map<String, Object>> data = null;
        try {
            data = jdbcTemplate.queryForList(queryParam.getSql());
        } catch (DataAccessException e) {
            e.printStackTrace();
            return ApiResult.fail(e.getMessage());
        }
        long elapsed = started.elapsed(TimeUnit.MILLISECONDS);
        Set<String> titleSet = new HashSet<>();
        if (!CollectionUtils.isEmpty(data)){
            titleSet = data.get(0).keySet();
        }
        QueryVo queryVo = QueryVo.builder()
                .data(data)
                .totalTime("共计耗时(s)：" + new BigDecimal(elapsed).divide(new BigDecimal(1000)).setScale(2,BigDecimal.ROUND_HALF_UP))
                .titleSet(titleSet)
                .build();
        return ApiResult.ok(queryVo);

        }
    @GetMapping("/insertCatalogue")
    public String insertCatalogue(Integer sqlNum){
        return this.service.insertCatalogue(sqlNum);
    }


    @GetMapping("/insertBaseData")
    public String insertBaseData(Integer sqlNum,Integer boundNum,Integer threadNum) throws InterruptedException {
        return this.service.insertBaseData(sqlNum,boundNum,threadNum);
    }

    }